package com.pattern.structural.composite.Class02;


import java.util.ArrayList;
import java.util.List;

/**
 * @Description
 * @Author Ping
 * @Date 2022/4/12 14:16
 **/
public class CompositeDemo {

    public static void main(String args[]) {

        Fruit fruitPlate = new FruitPlate() ;
        fruitPlate.addFruit(new Apple())
                .addFruit(new Orange()) ;
        fruitPlate.eat() ;




    }
}

/**
 * Abstract Element:
 */
abstract class Fruit {
    protected String name ;
    public abstract void eat() ;
    public abstract Fruit addFruit(Fruit fruit) ;
}


class FruitPlate extends Fruit {
    /**
     * composing relation:
     * 1. whole / part
     * 2. recursive relation
     */
    private List<Fruit> fruits ;

    public FruitPlate() {
        this.fruits = new ArrayList<>() ;
    }

    @Override
    public void eat() {
        for (Fruit fruit : this.fruits) {
            fruit.eat() ;
        }
    }

    @Override
    public Fruit addFruit(Fruit fruit) {
        this.fruits.add(fruit) ;
        return this ;
    }
}


class Orange extends  Fruit {
    @Override
    public void eat() {
        System.out.println("An orange can eat .") ;
    }

    @Override
    public Fruit addFruit(Fruit fruit) {
        System.out.println("Error, can not added any other fr;uit.") ;
        return null ;
    }
}

class Apple extends  Fruit {
    @Override
    public void eat() {
        System.out.println("An apple can eat .") ;
    }

    @Override
    public Fruit addFruit(Fruit fruit) {
        System.out.println("Error, can not added any other fr;uit.") ;
        return null ;
    }
}




